// src/lib/stores/contentRefreshStore.ts
import { writable, type Writable } from 'svelte/store';

/**
 * 1. 定义 Store 状态的 TS 接口（明确类型）
 */
export interface ContentRefreshStoreState {
	contentRefreshKey: number;
	refreshContent: () => void;
}

/**
 * 2. 工厂函数：创建 ContentRefresh Store（完善类型）
 */
export function createContentRefreshStore(): Writable<ContentRefreshStoreState> {
	// 初始状态（不含 refreshContent 方法，后续注入）
	const initialState: Omit<ContentRefreshStoreState, 'refreshContent'> = {
		contentRefreshKey: 0
	};

	// 创建 Store 时明确泛型类型为 ContentRefreshStoreState
	const { set, update, subscribe } = writable<ContentRefreshStoreState>({
		...initialState,
		refreshContent: () => {} // 临时占位
	});

	/**
	 * 3. 定义刷新方法（明确 update 回调的类型）
	 */
	const refreshContent: ContentRefreshStoreState['refreshContent'] = () => {
		// 为 update 回调的 currentState 指定类型：ContentRefreshStoreState
		update((currentState: ContentRefreshStoreState) => ({
			...currentState,
			contentRefreshKey: currentState.contentRefreshKey + 1 // 确保返回值符合接口
		}));
	};

	// 初始化 Store：注入真正的 refreshContent 方法（类型匹配）
	set({
		...initialState,
		refreshContent
	});

	return { subscribe, set, update };
}

/**
 * 4. 默认单例 Store
 */
export const contentRefreshStore = createContentRefreshStore();
